package com.spring.utils.api_v4.controller;

import com.alibaba.fastjson.JSONObject;
import com.spring.utils.api_v4.annotation.ResponseResult;
import com.spring.utils.api_v4.controller.ui.PwdForm;
import com.spring.utils.api_v4.controller.ui.RoleItem;
import com.spring.utils.api_v4.controller.ui.UserItem;
import com.spring.utils.api_v4.pojo.DeptInfo;
import com.spring.utils.api_v4.pojo.Password;
import com.spring.utils.api_v4.pojo.Role;
import com.spring.utils.api_v4.pojo.UserInfo;
import com.spring.utils.api_v4.pojo.response.BizException;
import com.spring.utils.api_v4.pojo.response.ResultCode;
import com.spring.utils.api_v4.service.ISystemService;
import com.spring.utils.api_v4.service.IUserService;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/api/user")
@RestController
@ResponseResult
@Log
public class UserController {
    @Autowired private ISystemService systemService;
    @Autowired private IUserService userService;

    /**
     * 添加用户角色
     * @param role
     * @return
     */
    @PostMapping("/role/save")
    public String saveUserRole(@Valid @RequestBody RoleItem role) {
        // 添加用户角色
        Role r = userService.addUserRole(role.getUserId(), role.getName());
        return r.getId();
    }

    /**
     * 修改密码
     * @param form
     * @return
     */
    @PostMapping("/changPwd")
    public boolean changePwd(@RequestHeader(name = "token") String userId, @Valid @RequestBody PwdForm form) {
        UserInfo user = systemService.findUserById(userId);
        if(user == null) {
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        // 获取用户密码
        Password pwd = systemService.getUserPwd(user);
        if(!form.getOldPwd().equals(pwd.getPassword())) {
            throw new BizException(ResultCode.USER_PWD_ERR);
        }
        pwd.setPassword(form.getNewPwd());
        // 修改密码
        systemService.savePwd(pwd);
        return true;
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @PostMapping("/pwd/reset/{userId}")
    public boolean resetPwd(@PathVariable String userId) {
        // 获取用户信息
        UserInfo user = systemService.getUserById(userId);
        if(user == null){
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        systemService.resetUserPwd(user);
        return true;
    }

    /**
     * 保存用户信息
     * @param userItem
     * @return
     */
    @PostMapping("/save")
    public String saveUser(@Valid @RequestBody UserItem userItem) {
        UserInfo user = systemService.findUserById(userItem.getId());
        if(user == null) {
            user = new UserInfo();
        }
        // 复制属性
        BeanUtils.copyProperties(userItem, user);
        // 检查部门是否存在
        DeptInfo dept = systemService.getDeptById(userItem.getDeptId());
        if(dept == null) {
            throw new BizException(ResultCode.DEPARTMENT_NOT_EXIST);
        }
        user.setDepart(dept);
        systemService.saveUser(user);
        return user.getId();
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @DeleteMapping("/delete/{userId}")
    public boolean deleteUser(@PathVariable String userId) {
        systemService.deleteUserById(userId);
        return true;
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/info/{userId}")
    public JSONObject userInfo(@PathVariable String userId) {
        UserInfo user = systemService.getUserById(userId);
        if(user == null) {
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        List<String> roles = systemService.getUserRoles(userId).stream().map(Role::getName).collect(Collectors.toList());
        JSONObject rs = new JSONObject();
        rs.put("id", user.getId());
        rs.put("name", user.getName());
        rs.put("roles", roles);
        return rs;
    }

    /**
     * 获取用户详情
     * @param userId
     * @return
     */
    @GetMapping("/detail/{userId}")
    public UserItem getUserDetail(@PathVariable String userId) {
        UserInfo user = systemService.getUserById(userId);
        if(user == null) {
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        UserItem ui = new UserItem();
        BeanUtils.copyProperties(user, ui);
        return ui;
    }

    /**
     * 查询部门用户列表
     * @param deptId
     * @return
     */
    @GetMapping("/list/dept/{deptId}")
    public List<UserItem> getUsersOfDept(@PathVariable int deptId) {
        List<UserInfo> users = systemService.getUsersByDeptId(deptId);
        return convertUsers(users);
    }

    /**
     * 查询部门员工列表
     * @param deptId
     * @return
     */
    @GetMapping("/staff/dept/{deptId}")
    public List<UserItem> getStaffOfDept(@PathVariable int deptId) {
        List<UserInfo> users = systemService.getUsersByDeptId(deptId)
                .stream().filter(user -> user.getRawRole().equals("普通职工"))
                .collect(Collectors.toList());
        return convertUsers(users);
    }

    /**
     * 查询部门干部列表
     * @param deptId
     * @return
     */
    @GetMapping("/cadres/dept/{deptId}")
    public List<UserItem> getCadresOfDept(@PathVariable int deptId) {
        List<UserInfo> users = systemService.getUsersByDeptId(deptId)
                .stream().filter(user -> user.getRawRole().equals("干部"))
                .collect(Collectors.toList());
        return convertUsers(users);
    }

    /**
     * 用户数据格式转换
     * @param users
     * @return
     */
    private List<UserItem> convertUsers(List<UserInfo> users) {
        return users.stream().map(user -> {
            UserItem ui = new UserItem();
            BeanUtils.copyProperties(user, ui);
            ui.setContractDate(new LocalDate[] {user.getContractStartTime(), user.getContractEndTime()});
            return ui;
        }).collect(Collectors.toList());
    }
}
